package com.fourinone.core;

import com.fourinone.utils.Setting;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.http.HttpHeaders;
import java.util.logging.Handler;

/**
 * @author szper
 * @version 1.0
 * @date 2019/10/17 23:44
 */
public class MasterInetServer {
    /**
     *
     * @param i ip
     * @param p port
     * @param q TCP连接最大并发数, 传 0 或负数表示使用默认值
     */
    static void start (String i, int p, int q) {
        try {
            HttpServer hs = HttpServer.create(new InetSocketAddress(i, p), q);
            hs.createContext("/", new AllHandler()); //根 url
            //hs.createContext("", )
            hs.start();
        } catch (IOException e) {
            System.out.println("|MasterInetServer|:|start|" + e.toString());
            //e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        MasterInetServer.start("localhost", 8888, 0);
    }
}
class AllHandler implements HttpHandler {

    @Override
    public void handle(HttpExchange exchange) throws IOException {

//        byte[] respContents = "Hello World".getBytes("UTF-8");
//        // 设置响应头
//        httpExchange.getResponseHeaders().add("Content-Type", "text/html; charset=UTF-8");
//        // 设置响应code和内容长度
//        httpExchange.sendResponseHeaders(200, respContents.length);
//
//        // 设置响应内容
//        httpExchange.getResponseBody().write(respContents);
//
//        // 关闭处理器, 同时将关闭请求和响应的输入输出流（如果还没关闭）
//        httpExchange.close();
        Headers responseHeaders = exchange.getResponseHeaders();
        responseHeaders.set("Content-Type", "text/html");
        ///WEB-INFO/err404.jsp
        //String response = Setting.getRequest(Setting.getProp("RSPE404"));
        String response = "WEB-INFO/err404.jsp";
        System.out.println(response);
        exchange.sendResponseHeaders(HttpURLConnection.HTTP_NOT_FOUND, response.length());
        OutputStream os = exchange.getResponseBody();
        os.write(response.getBytes());
        os.close();
    }
}
